package room_event

import (
	"github.com/spf13/cast"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/api"
	"longmen/server/internal/rpc/tencentim/cache"
	chat2 "longmen/server/internal/rpc/tencentim/chat"
	_const "longmen/server/pkg/common/helper/const"
	pb "longmen/server/pkg/protobuf"
	"strconv"
)

func HandlingAfterMessage(req *pb.CallbackReq, text, adminText, richData string) (ret *pb.CallbackResp, err error) {
	ret = &pb.CallbackResp{}
	//user, err := GetUser(req)
	//if err != nil {
	//	return utils.CallbackFailResp(nil, err.Error()), err
	//}

	//匿名用户也可以发言
	user, err := GetUser(req)
	if err != nil {
		iHeader := 0
		if len(req.From_Account) >= 10 {
			iHeader = len(req.From_Account) - 6
		} else {
			cache.SetClientBeforeLogin(req)
			user, err = GetUser(req)
		}
		if err != nil {
			user = &chat2.ClientUser{
				Platform:   0,
				UserId:     0,
				RoomId:     cast.ToInt(req.GroupId),
				Token:      "",
				ClientName: global.Lang.T("anonymous") + req.From_Account[iHeader:len(req.From_Account)], //random.String(5, anonymousNameChars),
				Avatar:     "",
				Level:      0,
				Vip:        0,
				UUID:       "",
				Props:      nil,
				Anonymouse: true,
				Role:       0,
				Permit:     0,
			}
		}
	}

	roomId, _ := strconv.Atoi(req.GroupId)
	global.Log.Debugf("HandlingAfterMessage GroupId:%v,roomId:%+v", req.GroupId, roomId)
	heat := cache.NewRoomHeat(roomId)
	heat.SetInc(_const.PopMsgCount, 1)
	heat.IncrSpeakCount(user.UserId)
	err = api.GetAPI().ChatHistory(adminText, user.UserId, roomId, req.MsgSeq)
	if err != nil {
		global.Log.Errorf("chatHistory Err:%v", err)
	}
	return SayAfter(user, roomId, req, text, richData), nil
}
